import vjmap, { Map } from "vjmap";
import { env } from "./env";
import { App, MapThreeLayer } from "vjmap3d";
import "vjmap/dist/vjmap.min.css";
import { initButtonGroup } from "./ui";
const createMapApp = async () => {
    let containerId = "map3dContainer";
    // @ts-ignore
    document.getElementById(containerId).style.background = env.background || (env.darkTheme ? "#2c3e50" : "rgb(200, 211, 220)")

    let svc = new vjmap.Service(env.serviceUrl, env.accessToken)
    if (env.workspace) {
        // 如果有工作区，切换至相对应的工作区
        svc.switchWorkspace(env.workspace)
    }
    // 打开地图
    let style =  env.darkTheme ? vjmap.openMapDarkStyle() : vjmap.openMapLightStyle();
    style.clipbounds =  Math.pow(2, 6) // 只传值，不传范围，表示之前的范围放大多少倍
    let res = await svc.openMap({
        mapid: env.mapId, // 地图ID
        version: env.version,
        // @ts-ignore
        mapopenway: env.mapopenway || vjmap.MapOpenWay.GeomRender, // 以几何数据渲染方式打开
        style 
    })
    if (res.error) {
        // 如果打开出错
        console.error(res.error)
    }
    // 获取地图范围
    let mapExtent = vjmap.GeoBounds.fromString(res.bounds);
    // 根据地图范围建立几何投影坐标系
    let prj = new vjmap.GeoProjection(mapExtent);

    // 地图对象
    let map = new vjmap.Map({
        container: containerId, // DIV容器ID
        style: svc.rasterStyle(), // 样式，这里是栅格样式
        center: prj.toLngLat(mapExtent.center()), // 设置地图中心点
        zoom: 7, // 设置地图缩放级别
        pitch: 45,
        antialias: true, // 反锯齿
        renderWorldCopies: false // 不显示多屏地图
    });

    // 关联服务对象和投影对象
    map.attach(svc, prj);
    await map.onLoad();

    // 创建3d图层
    let mapLayer = new MapThreeLayer(map, {
        stat: {
            show: true,
            left: "0"
        }
    });
    let app: App = mapLayer.app;
    map.addLayer(new vjmap.ThreeLayer({ context: mapLayer as any }));
    
    // 增加天空图层
    addSkyLayer(map);

    map.doubleClickZoom.disable(); // 禁止双击缩放
    return app;
}
export const initMap2d = async () => {
    let app = await createMapApp()
    
    await initButtonGroup(app)
    return app;
};

const addSkyLayer = (map: Map) => {
    const sky = new vjmap.SkyLayer({
        skyType: 'gradient',
        skyGradient: [
            'interpolate',
            ['linear'],
            ['sky-radial-progress'],
            0.8,
            'rgba(159, 251, 253, 1.0)',
            1,
            'rgba(0,0,0,0.1)'
        ],
        skyGradientCenter: [0, 0],
        skyGradientRadius: 100,
        skyOpacity: [
            'interpolate',
            ['exponential', 0.1],
            ['zoom'],
            0,
            0.3,
            22,
            1
        ]
    }
    )
    sky.addTo(map);
}